package foroweb.controllers;

import foroweb.ejb.AccionUsuario;
import foroweb.ejb.Busquedas;
import foroweb.entidades.Privado;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.*;
import javax.servlet.http.HttpSession;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

public class LoginBean implements Serializable{

    //Atributos
    private String nick;
    private String password;
    private AuthenticationManager authenticationManager;



    //Getters y Setters
    public String getNick() {
        return nick;
    }
    public void setNick(String nick) {
        this.nick = nick;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public AuthenticationManager getAuthenticationManager() {
        return authenticationManager;
    }
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }


    //Metodos
    public String doLog(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(nick, password);
        authToken.setDetails(authentication.getDetails());
        try {
            Authentication newAuth = authenticationManager.authenticate(authToken);
            SecurityContextHolder.getContext().setAuthentication(newAuth);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Bienvenido, " + ((User)newAuth.getPrincipal()).getUsername() ,null));
            return "/index.html";
	} catch (AuthenticationException ae) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Usuario no existe o contraseña es incorrecta.", ae.getMessage()+"/"+ae.getLocalizedMessage()+"/"+ae.toString()+"/"+ae.getCause()));
            return "/welcome.xhtml";
	}
    }
    public String logout() throws java.io.IOException {
        SecurityContextHolder.getContext().setAuthentication(null);
        ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
        HttpSession session = (HttpSession)ectx.getSession(false);
        session.invalidate();
        return "/index.html";
    }
}
